package service

// jwt token 实现

import (
	"context"
	"myapp/internal/consts"
	"myapp/internal/model"
	"time"

	"github.com/gogf/gf/v2/encoding/gbase64"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/golang-jwt/jwt/v5"
)

type sJwtToken struct{}

var localJwtToken *sJwtToken

func init() {
	localJwtToken = &sJwtToken{}
}

func JwtToken() *sJwtToken {
	return localJwtToken
}

// 创建token
func (u *sJwtToken) CreateToken(ctx context.Context, userId uint, username string) (tokenString string, err error) {
	// 生成token
	expire := time.Now().Add(6 * time.Hour)
	uc := &model.JwtClaims{
		Id:       userId,
		Username: username,
		RegisteredClaims: jwt.RegisteredClaims{
			ExpiresAt: jwt.NewNumericDate(expire),
		},
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, uc)
	tokenString, err = token.SignedString([]byte(consts.JwtKey))
	if err != nil {
		return "", err
	}

	tokenString = gbase64.EncodeString(tokenString)
	return tokenString, nil
}

func (u *sJwtToken) ParseToken(ctx context.Context, tokenString string) (claims *model.JwtClaims, err error) {
	if tokenString == "" {
		return nil, gerror.New("token is empty")
	}
	tokenString, err = gbase64.DecodeToString(tokenString)
	if err != nil {
		return nil, gerror.Wrap(err, "base64解析token失败")
	}

	tokenClaims, err := jwt.ParseWithClaims(tokenString, &model.JwtClaims{}, func(token *jwt.Token) (interface{}, error) {
		return []byte(consts.JwtKey), nil
	})
	if err != nil {
		return nil, gerror.Wrap(err, "Token解析失败")
	}

	if claims, ok := tokenClaims.Claims.(*model.JwtClaims); ok && tokenClaims.Valid {
		return claims, nil
	}
	// g.Log().Info(ctx, claims.ExpiresAt)
	return nil, gerror.New("token error")
}
